//
//  UIControl+Tool.swift
//  YuanJuBian
//
//  Created by PerhapYs on 2021/12/31.
//

import UIKit

extension UIControl{

    private struct AssociatedClickKeys {
        static var touchUpInside : String = "touchUpInside"
    }
    
    typealias PYClickBlock = () -> ()
    
    var py_clickBlock : PYClickBlock?{
        set{
            objc_setAssociatedObject(self, &AssociatedClickKeys.touchUpInside, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &AssociatedClickKeys.touchUpInside) as? UIControl.PYClickBlock
        }
    }

    func addClick(click:@escaping PYClickBlock){
        
        self.addTarget(self, action: #selector(PYClickEvent(_:)), for: .touchUpInside)
        self.py_clickBlock = click
    }
    @objc func PYClickEvent(_ btn:UIControl){
        
        guard let clickBlock = self.py_clickBlock else {
            return
        }
        clickBlock()
    }
}

// 扩大点击范围
extension UIControl{
    
    private struct AssociatedKeys {
        static var perEdge : String = "expandPerEdge"
        static var expandEdge : String = "expandEdge"
    }
    
    var expandEdge : UIEdgeInsets{
        set{
            return objc_setAssociatedObject(self, &AssociatedKeys.expandEdge, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            guard let value = objc_getAssociatedObject(self, &AssociatedKeys.expandEdge) as? UIEdgeInsets else {
                return .zero
            }
            return value
        }
    }
    var perEdge : CGFloat{
        
        set{
            self.expandEdge = UIEdgeInsets.init(top: perEdge, left: perEdge, bottom: perEdge, right: perEdge)
            return objc_setAssociatedObject(self, &AssociatedKeys.perEdge, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        
        get{
            guard let value = objc_getAssociatedObject(self, &AssociatedKeys.perEdge) as? CGFloat else {
                return 0
            }
            return value
        }
    }
    
    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        
        let newRect = CGRect.init(x: self.bounds.origin.x - self.expandEdge.left,
                                  y: self.bounds.origin.y - self.expandEdge.top,
                                  width: self.bounds.size.width + self.expandEdge.left + self.expandEdge.right,
                                  height: self.bounds.size.height + self.expandEdge.top + self.expandEdge.bottom)
        
        if newRect.equalTo(self.bounds){
            return super.point(inside: point, with: event)
        }
        
        return newRect.contains(point)
    }
}
